﻿using System;
using System.Threading;

namespace 线程的常用方法
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test2();
        }

        static void Test1()
        {
            Thread thread = new Thread(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}线程在运行中:{i}");

                }
            })
            { Priority = ThreadPriority.Normal, IsBackground = true };

            thread.Start();

            Console.WriteLine("Hello World!");

            thread.Join(); // 等待thread线程结束

            Console.WriteLine("Done");
        }

        static void Test2()
        {
            Thread thread = new Thread(() =>
            {
                try
                {
                    for (int i = 0; i < 20; i++)
                    {
                        Thread.Sleep(200);
                        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}线程在运行中:{i}");

                    }
                }
                catch (ThreadInterruptedException ex)
                {
                    Console.WriteLine("发生了中断异常");    
                }
                finally 
                {
                    Console.WriteLine("线程结束了");
                }
            })
            { Priority = ThreadPriority.Normal, IsBackground = true };

            thread.Start();

            Console.WriteLine("Hello World!");

            thread.Interrupt(); // 线程中断，会有一个异常。ThreadInterruptedException

            thread.Join();

            Console.WriteLine("Done");
        }

    }
}
